package com.platform.api;

import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.service.ApiGoodsService;
import com.platform.service.ApiOrderGoodsService;
import com.platform.service.ApiOrderService;
import com.platform.service.ApiProductService;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.utils.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "临时配送点相关")
@RestController
@RequestMapping("/api/dispatch")
public class ApiDispatchController extends ApiBaseAction {
    @Autowired
    private ApiOrderService orderService;
    @Autowired
    private ApiOrderGoodsService orderGoodsService;
    @Autowired
    private ApiGoodsService goodsService;
    @Autowired
    private ApiProductService productService;

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {

        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }

    /**
     * 获取订单列表
     */
    @ApiOperation(value = "获取订单列表")
    @IgnoreAuth
    @GetMapping("order/list")
    public Object list(
            @RequestParam(value = "shippingDate") Date shippingDate,
            @RequestParam(value = "userId", required = false) Integer userId) {
        //

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(shippingDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        Date start = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date end = calendar.getTime();

        Map params = new HashMap();
        params.put("page", 1);
        params.put("limit", Integer.MAX_VALUE);
        params.put("sidx", "id");
        params.put("order", "asc");
        params.put("order_status_gt", 201);
        if(userId != null) {
            params.put("user_id", userId);
        }
        params.put("pay_status", 2);
        params.put("shipping_time_start", start);
        params.put("shipping_time_end", end);

        //查询列表数据

        Query query = new Query(params);
        ArrayList<Map> shippingOrders = new ArrayList<>();
        List<OrderVo> orderEntityList = orderService.queryList(query);

        for (OrderVo item: orderEntityList) {
            Map orderGoodsParam = new HashMap();
            orderGoodsParam.put("order_id", item.getId());
            List<OrderGoodsVo> goodsList = orderGoodsService.queryList(orderGoodsParam);

            Map shippingOrder = new HashMap();
            shippingOrder.put("order", item);
            shippingOrder.put("orderGoods", goodsList);

            shippingOrders.add(shippingOrder);
        }

        int total = orderService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(shippingOrders, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }


    @ApiOperation(value = "获取订单列表")
    @IgnoreAuth
    @GetMapping("order/stat")
    public Object stat(
            @RequestParam(value = "shippingDate") Date shippingDate,
            @RequestParam(value = "userId", required = false) Integer userId) {
        //

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(shippingDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        Date start = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date end = calendar.getTime();

        Map params = new HashMap();
        params.put("page", 1);
        params.put("limit", Integer.MAX_VALUE);
        params.put("sidx", "id");
        params.put("order", "asc");
        params.put("order_status", 201);
        if(userId != null) {
            params.put("user_id", userId);
        }
        params.put("pay_status", 2);
        params.put("shipping_time_start", start);
        params.put("shipping_time_end", end);

        //查询列表数据

        Query query = new Query(params);
        ArrayList<Map> shippingOrders = new ArrayList<>();

        /*
        List<OrderVo> orderEntityList = orderService.queryList(query);

        Map<String, Integer> shippingStat = new HashMap<>();
        for (OrderVo item: orderEntityList) {
            Map orderGoodsParam = new HashMap();
            orderGoodsParam.put("order_id", item.getId());

            List<OrderGoodsVo> goodsList = orderGoodsService.queryList(orderGoodsParam);
            for(OrderGoodsVo goods: goodsList) {
                Integer goodsNumber = goods.getNumber();
                if( shippingStat.containsKey(goods.getGoods_name())) {
                    goodsNumber += shippingStat.get(goods.getGoods_name());
                }
                shippingStat.put( String.format("%s", goods.getGoods_name()), goodsNumber);
            }
        }

        List output = new ArrayList();
        for (String key: shippingStat.keySet())  {
            Map goods = new HashMap();
            goods.put("name", key);
            goods.put("quantity", shippingStat.get(key));
            output.add(goods);
        }
        */
        List<Map> output = orderGoodsService.shippingStatistics(query);

        return toResponsSuccess(output);
    }


    @ApiOperation(value = "修改订单")
    @IgnoreAuth
    @GetMapping("goods/update")
    public Object goodsUpdate(
            @RequestParam(value = "goods_id", required = false) Integer goodsId,
            @RequestParam(value = "is_new", required = false) Integer isNew,
            @RequestParam(value = "is_hot", required = false) Integer isHot,
            @RequestParam(value = "is_on_sale", required = false) Integer isOnSale,
            @RequestParam(value = "goods_number", required = false) Integer goodsNumber,
            @RequestParam(value = "retail_price", required = false) BigDecimal retailPrice) {

        GoodsVo goods = goodsService.queryObject(goodsId);

        if (goods == null) {
            return toResponsFail("产品不存在");
        }

        if(isHot != null) {
            goods.setIs_hot(Integer.valueOf(isHot));
        }
        if(isNew != null) {
            goods.setIs_new(Integer.valueOf(isNew));
        }
        if(isOnSale != null) {
            goods.setIs_on_sale(Integer.valueOf(isOnSale));
        }
        if(goodsNumber != null) {
            goods.setGoods_number(Integer.valueOf(goodsNumber));

            Map productParam = new HashMap();
            productParam.put("goods_id", goodsId);

            List<ProductVo> productList = productService.queryList(productParam);
            for(ProductVo product: productList) {
                product.setGoods_number(goodsNumber);
                productService.update(product);
            }
        }
        if(retailPrice != null) {
            goods.setRetail_price(retailPrice);

            Map productParam = new HashMap();
            productParam.put("goods_id", goodsId);

            List<ProductVo> productList = productService.queryList(productParam);
            for(ProductVo product: productList) {
                product.setRetail_price(retailPrice);
                productService.update(product);
            }
        }

        goodsService.update(goods);
        return toResponsMsgSuccess("修改订单成功");
    }
}
